package com.parsifal.server.socket;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import com.parsifal.server.listener.OnSocketReceiveListener;
import com.parsifal.server.listener.OnSocketSendListener;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by yangming on 17-3-31.
 */
public class Server {

    private static final String TAG = "Server";

    private HashMap<String, BluetoothSocket> mServerSockets = null;

    private OnSocketSendListener mOnSendListener = null;

    private OnSocketReceiveListener mOnReceiveListener = null;

    private HashMap<String, ExecutorService> mThreadPools = null;

    private int mIndex = 0;

    public void connect(BluetoothAdapter bluetoothAdapter, BluetoothDevice device) {
        if (null == mServerSockets) {
            mServerSockets = new HashMap<>();
        }
        if (null == mThreadPools) {
            mThreadPools = new HashMap<>();
        }
        try {
            final String address = device.getAddress();
            if (!mServerSockets.keySet().contains(address)) {
                ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
                mThreadPools.put(address, singleThreadExecutor);
                final SocketThread socketThread = new SocketThread(bluetoothAdapter, device) {
                    @Override
                    public void run() {
                        try {
                            BluetoothDevice device = getDevice();
                            String address = device.getAddress();
                            String name = device.getName();
                            BluetoothServerSocket bluetoothServerSocket = getBluetoothAdapter().listenUsingRfcommWithServiceRecord("btspp" + mIndex,
                                    UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                            mIndex++;
                            mServerSockets.put(address, bluetoothServerSocket.accept());
                            bluetoothServerSocket.close();

                            BluetoothSocket serverSocket = mServerSockets.get(address);
                            while (null != serverSocket) {
                                InputStream inputStream = serverSocket.getInputStream();
                                byte[] buffer = new byte[1024];
                                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                                int length = bufferedInputStream.read(buffer);
                                String clientMsg = new String(buffer, 0, length);
                                if (null != mOnReceiveListener) {
                                    mOnReceiveListener.onReceive(clientMsg);
                                }

                                OutputStream outputStream = serverSocket.getOutputStream();
                                String serverMsg = "hello " + name + ", " + clientMsg;
                                outputStream.write(serverMsg.getBytes());
                                outputStream.flush();
                                if (null != mOnSendListener) {
                                    mOnSendListener.onSend(serverMsg);
                                }
                            }
                        } catch (Exception e) {
                            try {
                                mServerSockets.get(address).close();
                                mServerSockets.remove(address);
                                mThreadPools.get(address).shutdownNow();
                                mThreadPools.remove(address);
                                Log.i(TAG, address + " 异常断开");
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                            e.printStackTrace();
                        }
                    }
                };
                singleThreadExecutor.execute(socketThread);
            }
            Log.i(TAG, "蓝牙服务端ON");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setOnSendListener(OnSocketSendListener listener) {
        mOnSendListener = listener;
    }

    public void setOnReceiveListener(OnSocketReceiveListener listener) {
        mOnReceiveListener = listener;
    }

    public void stopServer() {
        if (null != mThreadPools) {
            for (String address : mServerSockets.keySet()) {
                mThreadPools.get(address).shutdownNow();
            }
            mThreadPools.clear();
        }
        if (null != mServerSockets) {
            for (String address : mServerSockets.keySet()) {
                try {
                    mServerSockets.get(address).close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            mServerSockets.clear();
        }
    }

    public void closeSocket(BluetoothDevice device) {
        if (null != mServerSockets && null != device) {
            String address = device.getAddress();
            if (mServerSockets.keySet().contains(address)) {
                try {
                    mServerSockets.get(address).close();
                    mServerSockets.remove(address);
                    Log.i(TAG, address + " 正常断开");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (mThreadPools.keySet().contains(address)) {
                mThreadPools.get(address).shutdownNow();
                mThreadPools.remove(address);
            }
        }
    }
}
